package com.wzm.pet.service.impl;

import com.wzm.basic.domain.Point;
import com.wzm.basic.exception.BusinessException;
import com.wzm.basic.service.IBaiduAiAuditService;
import com.wzm.basic.util.*;
import com.wzm.order.domain.OrderPetAcquisition;
import com.wzm.order.mapper.OrderPetAcquisitionMapper;
import com.wzm.org.domain.Employee;
import com.wzm.org.domain.Shop;
import com.wzm.org.mapper.EmployeeMapper;
import com.wzm.org.mapper.ShopMapper;
import com.wzm.pet.domain.Pet;
import com.wzm.pet.domain.SearchMasterMsg;
import com.wzm.pet.domain.SearchMasterMsgAuditLog;
import com.wzm.pet.mapper.PetMapper;
import com.wzm.pet.mapper.SearchMasterMsgAuditLogMapper;
import com.wzm.pet.mapper.SearchMasterMsgMapper;
import com.wzm.pet.query.SearchMasterMsgQuery;
import com.wzm.pet.service.ISearchMasterMsgService;
import com.wzm.basic.service.impl.BaseServiceImpl;
import com.wzm.user.domain.Logininfo;
import com.wzm.user.domain.User;
import com.wzm.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private PetMapper petMapper;
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        //1.添加寻主消息到数据库【获取用户的id】
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);


        //2.审核 - 百度AI智能审核，没有人工审核 - BaiduAiAuditServiceImpl的方法
        //a.对name和address进行内容审核
        //b.对resources进行图片审核
        Boolean boo1 = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getAddress());
        Boolean boo2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());


        //3.审核通过
        if(boo1 && boo2){

            //b.添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(1);
            log.setMsgId(searchMasterMsg.getId());
            //  audit_id   --  自动审核没有审核人 - 系统
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);

            //c.获取当前用户最近的店铺，将该寻主消息分配给这个店铺 - 工具类
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            //注意：t_shop中的地址一定要真实，而且不能为null
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            //d.给店铺管理员发邮件或发短信通知它到指定的address去收购宠物
            if(nearestShop!=null){
//                SmsUtils.sendSms(nearestShop.getTel(),"你有新的订单，请到"+searchMasterMsg.getAddress()+"去接宠物");
                System.out.println("你有新的订单，请到"+searchMasterMsg.getAddress()+"去接宠物");
            }
            //e.如果没有这个店铺 - 不用管

            //a.修改状态state=1【审核成功待处理】
            searchMasterMsg.setState(1);
            if(nearestShop!=null){//找到了用户附近50公里以内的店铺
                searchMasterMsg.setShopId(nearestShop.getId());
            }
            searchMasterMsgMapper.update(searchMasterMsg);
            return new AjaxResult();

        }else{
            //4.审核失败 - 设置状态state=0【待审核=审核失败】，可以使用默认值 + 添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            //  audit_id   --  自动审核没有审核人 - 系统
            log.setNote("审核失败，内容非法");
            log.setState(0);
            searchMasterMsgAuditLogMapper.save(log);
            return new AjaxResult(false,"审核失败，内容非法");
        }
    }
    @Override
    public PageList<SearchMasterMsg> userQuery(SearchMasterMsgQuery query, HttpServletRequest request) {
        //获取用户的id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        //通过id将shopId置为null
        searchMasterMsgMapper.updateShopId(id);
    }

    @Override
    public void accept(Map<String, String> map) {
        long msgId = Long.parseLong(map.get("msgId"));
        long handler = Long.parseLong(map.get("handler"));
        String note = map.get("note");
        //1.校验：校验当前寻主消息是否有订单 - 有就说明当前寻主消息正在处理
        OrderPetAcquisition order = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if(order!=null){
            throw new BusinessException("当前寻主消息正在处理，请勿重复接单!!!");
        }

        //2.生成宠物保存到数据库
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgId);
        Pet pet = msg2Pet(msg);
        petMapper.save(pet);

        //3.生成收购订单 - 发短信或邮件告诉店铺人员去收回宠物
        OrderPetAcquisition tempOrder = createOrder(msg,pet,handler,note);
        orderPetAcquisitionMapper.save(tempOrder);

        //模拟发短信和邮件：handler = employee_id
        System.out.println("请到【"+msg.getAddress()+"】接回宠物");
        //省略线下：店铺人员去收回宠物
    }

    private Pet msg2Pet(SearchMasterMsg msg) {
        Pet pet = new Pet();
        pet.setName(msg.getName());
        pet.setCostprice(msg.getPrice());
        //saleprice - 市场价上架之前定义
        pet.setTypeId(msg.getPetType());
        pet.setResources(msg.getResources());
        pet.setState(0);
        pet.setShopId(msg.getShopId());
        pet.setUserId(msg.getUserId());
        pet.setSearchMasterMsgId(msg.getId());
        return pet;
    }

    private OrderPetAcquisition createOrder(SearchMasterMsg msg, Pet pet, long handler, String note) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(pet.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(note);
        Date date = new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000);
        order.setLastcomfirmtime(date);
        order.setPrice(msg.getPrice());
        //paytype - 现金支付
        order.setPetId(pet.getId());
        order.setUserId(pet.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(handler);
        order.setSearchMasterMsgId(msg.getId());
        return order;
    }
    @Override
    public PageList<SearchMasterMsg> Tohandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        //判断一个管理员是店铺管理员还是平台管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        //如果是店铺管理员就设置店铺id
        if(employee.getShop_id()!=null){//当前管理员是店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }
}
